<template>
  <div class="app-container">
    <!-- 查询模块 -->
    <div class="formDiv">
      <el-form ref="form" :inline="true" label-width="130px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="服务商姓名/手机">
              <el-input v-model="params.keyword" placeholder="请输入姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="提现状态">
              <el-select v-model="params.status" clearable>
                <el-option
                  v-for="item in StatusOption"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发放状态">
              <el-select v-model="params.send_status" clearable>
                <el-option
                  v-for="item in grantOption"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="提现时间">
              <el-date-picker
                v-model="time"
                type="daterange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" />
          <el-col :span="6">
            <el-form-item label="银行卡号">
              <el-input v-model="params.bank_card_num" placeholder="请输入手机号" clearable />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="转账来源">
              <el-select v-model="params.source" clearable>
                <el-option
                  v-for="item in bankOption"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>-->

          <el-col :span="6">
            <el-form-item label="提现金额">
              <div style="display: flex;">
                <el-input
                  v-model="params.withdrawal_amount_min"
                  style="width: 106px;"
                  placeholder="最低"
                  type="number"
                  min="1"
                  clearable
                  @keyup.native="proving($event)"
                />
                <span style="padding:0 5px;">—</span>
                <el-input
                  v-model="params.withdrawal_amount_max"
                  style="width: 106px;"
                  placeholder="最高"
                  type="number"
                  clearable
                  @keyup.native="proving($event)"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核时间">
              <el-date-picker
                v-model="time1"
                type="daterange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" />
          <el-col :span="14">
            <el-button type="primary" @click="Examination('',0)">批量审核</el-button>
          </el-col>
          <el-col :span="8" style="text-align: right;">
            <el-button type="primary" @click="searchFn">查询</el-button>
            <el-button type="primary" @click="excelEvent">导出</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- table -->
    <div v-loading="tableLoading" class="table">
      <h4 style="margin-top:20px">已选{{ multipleSelection.length }}笔，总计{{ withdrawalAmount }}元</h4>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55" v-if="flag" :selectable="selectable"></el-table-column> -->
        <el-table-column type="selection" width="55" :selectable="selectable" />
        <el-table-column type="index" align="center" label="序号" fixed />
        <el-table-column prop="realname" align="center" label="服务商姓名" />
        <el-table-column prop="username" align="center" label="服务商手机号">
          <!-- <template slot-scope="scope">
            <div>{{ scope.row.username | phonereg }}</div>
          </template>-->
        </el-table-column>
        <el-table-column prop="withdrawal_amount" align="center" label="提现金额" />
        <el-table-column prop="bank_name" align="center" label="提现银行" />
        <el-table-column prop="account_name" align="center" label="绑卡姓名" />
        <el-table-column prop="bank_card_num" align="center" label="提现银行卡号" />
        <el-table-column prop="apply_time" align="center" label="提现申请时间" />
        <el-table-column prop="audit_name" align="center" label="审核状态">
          <template slot-scope="scope">
            <!-- <span>{{scope.row.transStatusInt}}</span> -->
            <span>{{ scope.row.audit_name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="send_status_name" align="center" label="发放状态" />
        <el-table-column prop="return_msg" align="center" label="第三方返回" />
        <el-table-column prop="admin_remark" align="center" label="备注" />
        <el-table-column prop="approve_time" align="center" label="审核时间" />
        <el-table-column prop="approver_name" align="center" label="审核人" />
        <el-table-column fixed="right" width="100" label="操作" align="center">
          <template slot-scope="scope">
            <!-- <div> -->
            <el-button
              v-if="scope.row.check_button==1"
              type="text"
              @click="Examination(scope.row,0,scope.row.id)"
            >审核</el-button>
            <!-- </div> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagesCon">
      <div>
        <el-pagination
          :current-page="params.page"
          :page-sizes="[10, 20, 50, 100,200]"
          :page-size="params.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 审核 -->
    <el-dialog title="审核" :visible.sync="dialogVisible" width="468px">
      <el-form
        ref="ruleForm"
        :rules="ruleForm"
        :inline="true"
        label-width="80px"
        label-position="right"
        :model="datas"
      >
        <el-form-item label="审核意见" prop="radio">
          <el-radio-group v-model="datas.radio" @change="opinionChange">
            <p style="display: flex;">
              <!-- <el-radio v-if="istabledata" label="0">待审核</el-radio> -->
              <el-radio v-if="!istabledata" label="1">审核通过</el-radio>
              <el-radio label="0">审核驳回</el-radio>
              <!-- <el-radio v-if="!istabledata" label="2">审核驳回</el-radio> -->
            </p>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="datas.radio=='1'" label="转出银行" prop="region">
          <!-- <branklist @brankfun="brankfun"></branklist> -->
          <el-select v-model="datas.region">
            <el-option
              v-for="item in bankOption"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="datas.radio=='0'" label="驳回原因" prop="remark">
          <el-input v-model="datas.remark" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="isDisable" @click="rewardSure('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import branklist from "@/components/branklist";
import {
  withdraw_check_list,
  withdraw_init_data,
  withdraw_check,
  withdraw_check_export,
} from "@/api/WithdrawalAudit";
import commonFn from "@/utils/common";

export default {
  name: "Verification",
  components: {
    branklist,
  },
  // 过滤
  filters: {},
  data() {
    return {
      userId: sessionStorage.getItem("userId"), // 登录用户的id
      username: sessionStorage.getItem("username"), // 登录用户的名称
      isDisabled: false,
      timeval: 60,
      gongmallnum: 0,
      payroll: {},
      permissionJson: JSON.parse(localStorage.getItem("permissionJson")),
      ValuableFlaf: false,
      // loading层
      tableLoading: false,
      // 提交查询数据
      params: {
        // 1-美分享(plus)，2-美创家(服务商提现审核列表) 3-合伙人小程序（佣金）
        platform_id: 2,
        bank_card_num: "",
        source: "", //转账来源
        status: "",
        send_status: "",
        start_time: "",
        end_time: "",
        withdrawal_amount_min: "",
        withdrawal_amount_max: "",
        page: 1,
        size: 10,
      },
      // 修改按钮的当前行id
      ids: "",
      datas: { radio: "", remark: null, region: "" },
      bankdata: { bankRegion: "" },
      tableData: [],
      total: 0,
      time: [],
      time1: [],
      // 勾选的当前行数据
      rowInfo: null,
      // 勾选数据
      multipleSelection: [],
      // 修改银行卡id
      bankId: "",
      // 提现金额合计
      withdrawalAmount: 0,
      // 薪税宝账户余额
      accountBalance: "",
      dialogVisible: false,
      istabledata: true,
      dialogbrank: false,
      // 审核状态下拉框 0为待审核 1为审核成功 2为审核失败
      StatusOption: [],
      // 发放状态 0：待处理 1：成功 2：失败
      grantOption: [],
      bankOption: [
        // { id: "", name: "全部" },
        // { id: "6226661401701333", name: "6226661401701333" },
        // { id: "6226621407581295", name: "6226621407581295" },
        // { id: "127912425910301", name: "127912425910301" },
        // { id: "xb", name: "薪税宝" },
        // { id: "gongmall", name: "工猫" },
      ],
      bankChangeOption: [
        { id: "", name: "全部" },
        { id: "6226661401701333", name: "6226661401701333" },
        { id: "6226621407581295", name: "6226621407581295" },
        { id: "127912425910301", name: "127912425910301" },
      ],
      // 校验规则captcha
      ruleForm: {
        radio: [
          { required: true, message: "请选择审核意见", trigger: "change" },
        ],
        remark: [
          { required: true, message: "驳回原因为必填项", trigger: "blur" },
        ],
        captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
        region: [
          { required: true, message: "请选择银行卡", trigger: "change" },
        ],
      },
      bankRules: {
        bankRegion: [
          { required: true, message: "请选择转出银行卡", trigger: "change" },
        ],
      },
      // 选择的银行卡号
      banckNumber: "",
      // 区分审核、修改弹窗的开关
      typeFlag: "",
      isDisable: false, // 表单重复提交
    };
  },
  inject: ["reload"],
  watch: {
    time(val) {
      this.params.start_time = val ? val[0] : "";
      this.params.end_time = val ? val[1] : "";
    },
    time1(val) {
      this.params.approve_time_start = val ? val[0] : "";
      this.params.approve_time_end = val ? val[1] : "";
    },
  },
  //新加路由保存参数
  beforeRouteLeave(to, from, next) {
    // const answer = window.confirm("当前页面搜索条件将会被保存");
    //更新 put
    let keyname = this.$route.name;
    let value = JSON.stringify(this.params);
    sessionStorage.setItem(keyname, value);
    next();
  },
  mounted() {
    // 获取默认列表
    if (sessionStorage.getItem(this.$route.name)) {
      this.params = JSON.parse(sessionStorage.getItem(this.$route.name));
    }
    this.getList(this.params);
    this.getSelectList();
    // this.accountsBalance();
    // this.getBalanceByGongmall();
  },
  methods: {
    // 按钮权限
    hasPermission(e) {
      return window.helper.hasPermission(e);
    },
    // 最小金额输入限制
    proving(e) {
      var keynum = window.event ? e.keyCode : e.which; // 获取键盘码
      var keychar = String.fromCharCode(keynum); // 获取键盘码对应的字符
      if (keynum == 189 || keynum == 190 || keynum == 109) {
        this.$message.warning("禁止输入小数以及负数");
        e.target.value = " ";
      }
    },
    // 复选框禁用控制
    selectable(row, index) {
      if (row.check_button == 1) {
        return true;
      } else {
        return false;
      }
    },
    // checkbox(row){
    //   console.log(row.row.transStatus)
    //   if(row.row.transStatus.indexOf("成") == -1){
    //     return "mycell"
    //   }
    // },
    // 提现审核列表里面的下拉框初始数据
    getSelectList() {
      withdraw_init_data().then((res) => {
        console.log("res", res);
        if (res.data.code == 200) {
          this.StatusOption = res.data.data.status_arr;
          // 审核状态下拉数据
          this.StatusOption.unshift({ id: "", name: "全部" });
          // 银行卡下拉数据
          this.bankOption = res.data.data.source_arr;
          // this.bankOption.unshift({id:"",name:"全部"})
          // 发放状态
          console.log(res.data.data.send_status_arr);
          this.grantOption = res.data.data.send_status_arr;
          this.grantOption.unshift({ id: "", name: "全部" });
        }
      });
    },
    // 服务商列表
    getList(e) {
      this.tableLoading = true;
      const datas = e;
      withdraw_check_list(datas)
        .then((res) => {
          // console.log("res", res);
          if (res.data.code == 200) {
            this.tableData = res.data.data;
            this.total = res.data.meta.total;
          } else {
            this.$message.error(res.data.msg);
          }
          this.tableLoading = false;
        })
        .catch((error) => {
          this.$message.error(error);
          this.tableLoading = false;
        });
    },
    // 薪宝账户余额查询
    accountsBalance() {
      accountsBalance().then((res) => {
        // console.log(res);
        this.accountBalance = res.data.data;
      });
    },
    // 查询
    searchFn() {
      this.params.page = 1;
      this.getList(this.params);
    },
    // 导出
    excelEvent() {
      let datas = { ...this.params };
      delete datas.page;
      delete datas.size;
      withdraw_check_export(datas)
        .then((res) => {
          commonFn.downFile("服务商提现导出", res);
        })
        .catch((err) => {
          this.errorStatus(err.msg);
        });
    },
    // 转出银行
    brankfun(datas) {
      // console.log(datas + "-----银行列表");
      this.banckNumber = datas;
      this.params.bankCard = datas;
    },
    // 单选框勾选
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(val);
      if (val.length >= 1) {
        const arr1 = [];
        this.multipleSelection.forEach((item) => {
          arr1.push(item.withdrawal_amount);
        });
        this.withdrawalAmount = arr1.reduce((a, b) => {
          return a - 0 + (b - 0);
        });
      } else {
        this.withdrawalAmount = 0;
      }

      // console.log(this.result)
      // this.withdrawalAmount = result;
    },
    // 审核弹窗监听radio切换
    opinionChange(val) {
      this.datas.radio = val;
      this.$refs.ruleForm.clearValidate();
    },
    // 审核、修改弹框
    Examination(datas, type, id) {
      // type:0  审核
      // type:0 datas有值 待审核
      // type:1  修改银行卡
      this.datas.radio = "";
      this.datas.remark = "";
      this.datas.region = "";
      this.ids = id;
      // 弹窗确认按钮恢复
      this.isDisable = false;
      // console.log(this.ids);
      // 审核
      if (type == 0) {
        this.rowInfo = datas;
        this.ValuableFlaf = true;
      }

      if (datas) {
        // 有值table 页面
        this.dialogVisible = true;
        this.ValuableFlaf = true;
      } else {
        // 列表页的群体操作
        if (this.multipleSelection.length >= 1) {
          this.dialogVisible = true;
        } else {
          this.$message({
            message: "请先勾选需要审核的数据",
            type: "warning",
          });
        }
      }
      this.istabledata = type;

      this.typeFlag = type;
      // console.log(this.typeFlag);
    },
    // 审核通过、审核驳回、待审核传参
    change(status, flag) {
      const data = {
        admin_username: this.username,
        admin_id: this.userId,
        platform_id: this.params.platform_id,
        opt: this.datas.radio,
        source: this.datas.region,
        remark: this.datas.remark,
        relation_ids: [],
      };
      if (flag) {
        // 当flag为真时，修改的id参数
        data.relation_ids.push(this.ids);
        // console.log(11);
      } else {
        const arr = [];
        if (this.multipleSelection.length >= 1) {
          // console.log('dianji--------');
          // 批量审核
          this.multipleSelection.forEach((datas) => {
            // console.log('datas',datas);
            arr.push(datas.id);
          });
          // console.log('arr',arr);
          data.relation_ids = JSON.stringify(arr);
          // console.log(22);
        } else {
          // 选择每一行的审核
          data.relation_ids.push(this.rowInfo.id);
          // console.log(33)
          data.relation_ids = JSON.stringify(data.relation_ids);
        }
      }
      this.AuditPass(data);
      // 审核通过时调用
      // console.log(this.datas.radio);
      // if (this.datas.radio == 1) {
      //   this.AuditPass(data);
      //   // 审核驳回及待审核
      // } else if (this.datas.radio == 2) {
      //   data.transStatus = 2;
      //   this.Reject(data);
      // } else {
      //   data.transStatus = 0;
      //   this.Reject(data);
      // }
      // console.log(this.datas.radio);
    },

    // 审核确定
    rewardSure(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert("submit!");
          console.log("审核");
          // 审核（列表上方）
          if (this.typeFlag == 0) {
            // console.log(this.datas.radio);
            if (this.datas.radio == 1) {
              // this.datas.remark=""
              this.change(1, false);
              this.$refs.ruleForm.resetFields();
            } else {
              // this.datas.region=""
              this.change(0, false);
              this.$refs.ruleForm.resetFields();
            }
            // 修改（每一行）
          } else {
            this.change(0, true);
          }
        } else {
          this.$message({
            showClose: true,
            message: "有必填项没填写!",
            type: "warning",
          });
          return false;
        }
      });
      this.dialogVisible = false;
    },

    // 批量审核通过/单行审核通过、复用请求
    AuditPass(e) {
      this.isDisable = true;
      const datas = e;
      withdraw_check(datas)
        .then((res) => {
          console.log(res);
          // this.isDisable = false;

          if (res.data.code == 200) {
            this.$message.success(res.data.msg);
            this.getList(this.params);
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((error) => {
          this.$message.error(error);
          // 请求异常时释放按钮
          this.isDisable = false;
          this.tableLoading = false;
        });
    },
    // 审核驳回、待审核复用请求
    // Reject(e) {
    //   const datas = e;
    //   Reject(datas)
    //     .then((res) => {
    //       // console.log(res)
    //       if (!res.data.code) {
    //         this.getList(this.params);
    //       } else {
    //         this.$message.error(res.data.msg);
    //       }
    //     })
    //     .catch((error) => {
    //       this.$message.error(error);
    //       this.tableLoading = false;
    //     });
    // },
    // 改变页面条数
    handleSizeChange(val) {
      // this.params.pageNum = 1;
      this.params.size = val;
      this.getList(this.params);
    },
    // 选择页数
    handleCurrentChange(val) {
      this.params.page = val;
      this.getList(this.params);
    },
  },
};
</script>
<style scoped>
/* 分页 */
.pagesCon {
  height: 40px;
  margin-top: 20px;
}
.pagesCon > div {
  float: right;
}
/* 表单样式修改 */
.el-range-editor--medium.el-input__inner {
  width: 236px;
}
.el-table .cell,
.el-table th div {
  padding-right: 10px;
  overflow: hidden;
  text-overflow: clip;
}
h4 {
  color: #606266;
  font-size: 16px;
}
</style>
